package com.guchenbo.nacos.spring.boot;

import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationPreparedEvent;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.core.env.Environment;

@SpringBootApplication
@NacosPropertySource(dataId = "example", autoRefreshed = true)
public class NacosBootApplication {
    protected static final Logger log = LoggerFactory.getLogger(NacosBootApplication.class);

    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(NacosBootApplication.class);
        application.addListeners(new GcbApplicationListener());
        application.run(args);
    }

    public static class GcbApplicationListener implements SmartApplicationListener {

        @Override
        public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
            return ApplicationPreparedEvent.class.isAssignableFrom(eventType)
                            || ApplicationStartedEvent.class.isAssignableFrom(eventType);
        }

        @Override
        public void onApplicationEvent(ApplicationEvent event) {
            if (event instanceof ApplicationPreparedEvent) {
                ApplicationPreparedEvent applicationPreparedEvent = (ApplicationPreparedEvent) event;
                Environment environment = applicationPreparedEvent.getApplicationContext().getEnvironment();
                log.info("gcb.nacos.name = {}", environment.getProperty("gcb.nacos.name"));
            }
            if (event instanceof ApplicationStartedEvent){
                ApplicationStartedEvent applicationStartedEvent = (ApplicationStartedEvent) event;
                Environment environment = applicationStartedEvent.getApplicationContext().getEnvironment();
                log.info("gcb.nacos.name = {}", environment.getProperty("gcb.nacos.name"));
            }
        }
    }
}
